package com.github.binarywang.demo.wx.pay.config;

import com.github.binarywang.demo.wx.pay.mp.domain.Mp;
import com.github.binarywang.demo.wx.pay.mp.mapper.MpMapper;
import com.github.binarywang.demo.wx.pay.mp.service.MpService;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Binary Wang
 */
@Configuration
@ConditionalOnClass(WxPayService.class)
@EnableConfigurationProperties(WxPayProperties.class)
@AllArgsConstructor
public class WxPayConfiguration {
  private WxPayProperties properties;
  private MpMapper mpMapper;









  @Bean
  public Map<String,WxPayService> wxPayServiceMap(){
    Map<String,WxPayService> map=new HashMap<>();
    List<Mp> listMp=mpMapper.selectList(null);
    for(int i=0;i<listMp.size();i++){
      Mp mp=listMp.get(i);

      WxPayConfig payConfig = new WxPayConfig();
      payConfig.setAppId(StringUtils.trimToNull(mp.getAppid()));
      payConfig.setMchId(StringUtils.trimToNull(mp.getMchid()));
      payConfig.setMchKey(StringUtils.trimToNull(mp.getMchkey()));
      payConfig.setSubAppId(null);
      payConfig.setSubMchId(null);
      payConfig.setKeyPath(StringUtils.trimToNull(mp.getKeypath()));

      // 可以指定是否使用沙箱环境
      payConfig.setUseSandboxEnv(false);

      WxPayService wxPayService = new WxPayServiceImpl();
      wxPayService.setConfig(payConfig);
      map.put(mp.getAppid(),wxPayService);


    }

    return map;
  }



}
